package 树;

import 集合.TreeMap;

public class Trie {

    private class Node{
        public boolean isWord;
        public int count;
        public TreeMap<Character,Node> nexts;

        public Node(){
            isWord = false;
            nexts =  new TreeMap<>();
            count = 0;
        }
    }

    private Node root;
    private int size; //不重复的单词
    private int totalSize; // 重复的
    public Trie(){
        root = new Node();
        size = 0;
    }

    public int size(){
        return size;
    }

    public int totalSize(){
        return totalSize;
    }

    public void add(String word){
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!cur.nexts.contains(c)){
                cur.nexts.put(c,new Node());
            }
            cur = cur.nexts.get(c);
        }
        if (!cur.isWord){
            cur.isWord = true;
            size++;
        }
        cur.count++;
        totalSize++;
    }

    public int count(String word){
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!cur.nexts.contains(c)){
                return 0;
            }
            cur = cur.nexts.get(c);
        }
        return cur.count;
    }

    public boolean contains(String word){
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!cur.nexts.contains(c)){
                return false;
            }
            cur = cur.nexts.get(c);
        }
        return cur.isWord;
    }

    public boolean isPrefix(String prefix){
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (!cur.nexts.contains(c)){
                return false;
            }
            cur = cur.nexts.get(c);
        }
        return true;
    }
}
